package com.lin.gameserver.handler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.lin.gameserver.protobuf.CommandId;
import com.lin.gameserver.protobuf.ErrorCode;
import com.lin.gameserver.protobuf.MessageWrapper;
import com.lin.gameserver.session.GameSession;
import com.lin.gameserver.websocket.MessageLogger;
import com.lin.proto.ReqHeartbeatMessage;
import com.lin.proto.ResHeartbeatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 心跳消息处理器
 */
public class HeartbeatHandler implements MessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);
    
    @Override
    public int getCommandId() {
        return CommandId.CMD_HEARTBEAT_REQ;
    }
    
    @Override
    public boolean handle(GameSession session, MessageWrapper wrapper) {
        try {
            long startTime = System.currentTimeMillis();
            
            // 解析心跳请求
            ReqHeartbeatMessage request = wrapper.parseRequestBody(ReqHeartbeatMessage.parser());
            
            // 更新会话活动时间
            session.updateActiveTime();
            
            // 计算延迟
            long clientTime = request.getClientTime();
            long serverTime = System.currentTimeMillis();
            int delay = (int) (serverTime - clientTime);
            
            // 构建心跳响应
            ResHeartbeatMessage response = ResHeartbeatMessage.newBuilder()
                    .setServerTime(serverTime)
                    .setDelay(delay)
                    .build();
            
            // 设置响应消息
            wrapper.setResponseBody(response);
            
            // 记录处理时间
            long processTime = System.currentTimeMillis() - startTime;
            MessageLogger.logProcessTime(session.getSessionId(), wrapper.getCmd(), processTime);
            
            if (logger.isDebugEnabled()) {
                logger.debug("Heartbeat from client: {} ms, delay: {} ms", clientTime, delay);
            }
            
            return true;
        } catch (InvalidProtocolBufferException e) {
            logger.error("Failed to parse heartbeat request", e);
            wrapper.setErrorCode(ErrorCode.ERROR_PROTOCOL);
            return false;
        }
    }
    
    @Override
    public boolean requireAuthentication() {
        // 心跳消息不需要认证
        return false;
    }
} 